﻿using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Media;

namespace SilverlightHtmlTextBlock
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
            // Register object for JavaScript access
            HtmlPage.RegisterScriptableObject("Harness", this);

#if CREATE_IN_CODE
            // Create a new HtmlTextBlock in code and mirror the existing XAML one
            var htmlTextBlockFromCode = new HtmlTextBlock();
            htmlTextBlockFromCode.Width = htmlTextBlock.Width;
            htmlTextBlockFromCode.Height = htmlTextBlock.Height;
            htmlTextBlockFromCode.TextWrapping = htmlTextBlock.TextWrapping;
            htmlTextBlockFromCode.Foreground = new SolidColorBrush { Color = Colors.Gray };

            // Replace the XAML HtmlTextBlock with the code one
            var htmlTextBlockCanvas = htmlTextBlock.Parent as Canvas;
            htmlTextBlockCanvas.Children.Remove(htmlTextBlock);
            htmlTextBlockCanvas.Children.Add(htmlTextBlockFromCode);
            htmlTextBlock = htmlTextBlockFromCode;
#endif
        }

        [ScriptableMember]
        public void SetText(string text, string fontFamily, string fontSizeString)
        {
            // Parse font size passed in as string
            var fontSize = double.Parse(fontSizeString);

            // Apply changes to TextBlock
            textBlock.Text = text;
            textBlock.FontFamily = new FontFamily(fontFamily);
            textBlock.FontSize = fontSize;

            // Apply changes to HtmlTextBlock
            htmlTextBlock.Text = text;
            htmlTextBlock.FontFamily = new FontFamily(fontFamily);
            htmlTextBlock.FontSize = fontSize;
        }
    }
}
